package cool.taomu.toolkit.demo.stock.listener

import com.google.common.eventbus.Subscribe
import cool.taomu.toolkit.demo.stock.listener.entity.StockDataEvent
import java.time.LocalDate
import cool.taomu.toolkit.demo.stock.entity.StockHistory
import com.google.inject.Inject
import org.jooq.DSLContext
import cool.taomu.toolkit.stock.dao.jooq.tables.TaomuStockTradingSignals
import cool.taomu.toolkit.stock.dao.jooq.enums.TaomuStockTradingSignalsIndicatorType
import cool.taomu.toolkit.stock.dao.jooq.enums.TaomuStockTradingSignalsSignalType

abstract class BaseSignalListener {

	@Inject
	DSLContext dsl

	@Subscribe
	def void onEventAsync(StockDataEvent event) {
		process(event)
	}

	def protected abstract void process(StockDataEvent event);

	def protected void saveSignal(String code, LocalDate date, String type, String signalType, double price,
		double value) {
		dsl.insertInto(TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS).set(
			TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS.CODE,
			code
		).set(
			TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS.INDICATOR_TYPE,
			TaomuStockTradingSignalsIndicatorType.valueOf(type)
		).set(
			TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS.SIGNAL_TYPE,
			TaomuStockTradingSignalsSignalType.valueOf(signalType)
		).set(
			TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS.SIGNAL_DATE,
			date
		).set(
			TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS.PRICE,
			price
		).set(
			TaomuStockTradingSignals.TAOMU_STOCK_TRADING_SIGNALS.INDICATOR_VALUE,
			value
		).execute
	}

	protected def boolean isBottom(StockHistory c, StockHistory p, StockHistory b) {
		return c.getLow() < p.getLow() && p.getLow() <= b.getLow();
	}

	protected def boolean isTop(StockHistory c, StockHistory p, StockHistory b) {
		return c.getHigh() > p.getHigh() && p.getHigh() >= b.getHigh();
	}
}
